<?php


namespace app\admin\model;


use app\common\traits\ActionRecordTrait;
use app\crm\model\FollowRecord;
use think\facade\Cache;
use think\facade\Db;

class MinProgramFans extends Common
{

    use ActionRecordTrait;

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'mini_program_fans';

    /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-28 9:15
     */
    public function getDataList(array $request): array
    {
        try {
            $userId           = $request['user_id'] ?? 0;
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            $bindStatus  = $request['bind_status'] ?? 0;
            $searchType  = $request['search_type'] ?? 1;
            $searchValue = isset($request['search_value']) && trim($request['search_value']) ? trim($request['search_value']) : '';
            $where       = [];

            // 获取客户数据权限 的客户ID
            $dataAuthCustomerId = (new \app\crm\model\Customer())->getDataAuthCustomer($userId, 'min_user');
            if (!in_array('all', $dataAuthCustomerId) && $searchType != 4) {
                // 排除搜索客户
                array_push($dataAuthCustomerId, 0); // 把未分配的也要显示
                array_push($where, ['m.customerId', 'in', $dataAuthCustomerId]);
            }

            $bindStatusArr = ['1' => '>', '2' => '='];
            if (array_key_exists($bindStatus, $bindStatusArr)) {
                array_push($where, ['m.customerId', $bindStatusArr[$bindStatus], 0]);
            }
            if ($searchValue) {
                $searchTypeArr = [
                    '1' => ['m.nickName', 'like', '%' . $searchValue . '%'],
                    '2' => ['m.telephone', '=', $searchValue],
                    '3' => ['m.openId', '=', $searchValue],
                    '4' => ['c.name', 'like', '%' . $searchValue . '%']
                ];
                if (array_key_exists($searchType, $searchTypeArr)) {
                    array_push($where, $searchTypeArr[$searchType]);
                    if ($searchType == 4) {
                        // 搜索客户
                        !in_array('all', $dataAuthCustomerId) && array_push($where, ['m.customerId', 'in', $dataAuthCustomerId]);
                    }
                } else {
                    array_push($where, ['m.id', '=', 0]);
                }
            }

            $querySql  = $this->where($where)->alias('m')
                ->join('crm_customer c', 'c.customer_id = m.customerId', 'LEFT');

            $dataCount = $querySql->count();
            if ($dataCount) {
                $field = ['m.id' => 'min_id', 'm.openId', 'm.nickName', 'm.gender', 'm.avatarUrl',
                    'm.customerId' => 'customer_id', 'c.name' => 'customer_name', 'c.king_no',
                    'm.create_time','m.telephone'];
                $list  = $querySql->field($field)->order('m.id DESC')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
                $genderArr = ['0' => '未知', '1' => '男', '2' => '女'];
                foreach ($list as $key => $val) {
                    $list[$key]['gender']           = $genderArr[$val['gender']] ?? '';
                    $list[$key]['bind_status_name'] = $val['customer_id'] > 0 ? '已绑定' : '未绑定';
                    unset($list[$key]['customer_id']);
                }
            }

            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return $data;
        } catch (\Exception $e) {
        }

        $this->error = '暂无此数据';
        return [];
    }

    /**
     * 详情
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-28 13:39
     */
    public function getDataInfo(array $request): array
    {
        try {
            $minId = $request['min_id'] ?? 0;
            if (!$minId) {
                $this->error = '参数错误';
                return [];
            }

            $field = ['m.id' => 'min_id', 'm.openId', 'm.nickName', 'm.gender', 'm.avatarUrl', 'm.customerId',
                'm.create_time', 'c.name' => 'customer_name', 'c.king_no','m.telephone'];
            $info  = $this->where('m.id', '=', $minId)->alias('m')
                ->join('crm_customer c', 'c.customer_id = m.customerId', 'LEFT')
                ->field($field)->find();
            if (!$info) {
                $this->error = '用户信息不存在';
                return [];
            }

            $genderArr                = ['0' => '未知', '1' => '男', '2' => '女'];
            $info['gender']           = $genderArr[$info['gender']];
            $info['bind_status_name'] = $info['customerId'] > 0 ? '已绑定' : '未绑定';
            unset($info['customerId']);

            $this->error = '获取成功';
            return $info->toArray();
        } catch (\Exception $e) {
        }

        $this->error = '编辑失败';
        return [];
    }

    /**
     * 选择客户
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-28 13:57
     */
    public function getCustomerDataList(array $request): array
    {
        try {
            $userId = $request['user_id'] ?? 0;
            $name   = isset($request['name']) && trim($request['name']) ? trim($request['name']) : '';
            $list   = [];
            if ($name) {

                // 获取客户数据权限 的客户ID
                $dataAuthCustomerId = (new \app\crm\model\Customer())->getDataAuthCustomer($userId, 'min_user');

                $where = [
                    ['name', 'like', '%'.$name.'%'],
                    ['sign_up_number', '<>', '']
                ];
                !in_array('all', $dataAuthCustomerId) && array_push($where, ['customer_id', 'in', $dataAuthCustomerId]);
                $field = ['customer_id', 'name'];
                $list  = (new \app\crm\model\Customer())->getCustomerList($where, $field);
            }

            $this->error = '获取客户成功';
            $data['data'] = $list ?: [];
            return $data;
        } catch (\Exception $e) {
        }

        $this->error = '获取客户失败';
        return [];
    }

    /**
     * 绑定客户
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-06-28 14:02
     */
    public function bindSaveData(array $request): bool
    {
        try {
            $minId      = isset($request['min_id']) && intval($request['min_id']) ? intval($request['min_id']) : 0;
            $customerId = isset($request['customer_id']) && intval($request['customer_id']) ? intval($request['customer_id']) : 0;
            if (!$minId || !$customerId) {
                $this->error = '参数错误';
                return false;
            }

            $field = [];
            $info  = $this->where('id', '=', $minId)->field($field)->find();
            if (!$info) {
                $this->error = '用户信息不存在';
                return false;
            }

            $data = [
                'customerId'  => $customerId,
                'update_time' => date('Y-m-d H:i:s')
            ];
            $bool = $this->where('id', '=', $minId)->update($data);
            if ($bool) {
                /*更新小程序缓存*/
                $fansInfo = Cache::get('mfans:MiniProgram-'.$request['min_id']);
                if( !empty($fansInfo) ){
                    $scode =  Db::name('crm_customer')->where('customer_id', '=', $request['customer_id'])->value('sign_up_number','');
                    Cache::set('mfans:MiniProgram-'.$request['min_id'],array_merge($fansInfo,['customerId'=>$request['customer_id'],'scode'=>$scode]));
                }

                // 操作记录
                $customerIdArr = [$info['customerId'], $customerId];
                $customerList  = Db::name('crm_customer')->where('customer_id', 'in', $customerIdArr)->column('name', 'customer_id');
                $logCode       = json_encode($data, JSON_UNESCAPED_UNICODE);
                if (!$info['customerId']) {
                    $newCustomer   = $customerList[$customerId] ?? '';
                    $logContentStr = "将 '客户绑定' 修改为 " . $newCustomer;
                } else {
                    $oldCustomer   = $customerList[$info['customerId']] ?? '';
                    $newCustomer   = $customerList[$customerId] ?? '';
                    $logContentStr = "将 '客户绑定' 由 " . $oldCustomer . " 修改为 " . $newCustomer;
                }
                $this->addActionRecord($request['user_id'], 'admin_min_program_fans_bind', $minId, $logContentStr, 'admin', 'min_user', $logCode);

                $this->error = '绑定成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '绑定失败';
        return false;
    }

    /**
     * 操作记录
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-28 14:21
     */
    public function getRecordList(array $request): array
    {
        $minId = $request['min_id'] ?? 0;
        if (!$minId) {
            $this->error = '参数错误';
            return [];
        }

        $page  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $limit = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
        return $this->getActionRecordListByPage($minId, 'admin', 'min_user', 0, $page, $limit);
	}

    /**
     * 添加跟进
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-06-28 14:26
     */
    public function addFollow(array $request): bool
    {
        try {
            $minId       = $request['min_id'] ?? 0;
            $contentType = $request['content_type'] ?? 0;
            if (!$minId || !$contentType) {
                $this->error = '参数错误';
                return false;
            }

            $customerId = $this->where('id', '=', $minId)->value('customerId');
            $request['obj_id']      = $minId;
            $request['follow_type'] = 5;
            $request['customer_id'] = $customerId ?: 0;

            // 调用添加跟进
            $followModel = new FollowRecord();
            $bool        = $followModel->addData($request);
            if ($bool) {
                $this->error = '添加成功';
                return true;
            }

            $this->error = $followModel->getError();
        } catch (\Exception $e) {
            $this->error = '添加失败';
        }

        return false;
	}

    /**
     * 跟进列表
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-28 14:54
     */
    public function getFollowList(array $request): array
    {
        $minId = $request['min_id'] ?? 0;
        if (!$minId) {
            $this->error = '参数错误';
            return [];
        }

        $request['no_page'] = 1; // 不分页
        $request['map']     = [
            ['field' => 'obj_id', 'value' => $minId, 'type' => '='],
            ['field' => 'follow_type', 'value' => 5, 'type' => '=']
        ];
        $followModel = new FollowRecord();
        $data        = $followModel->getDataList($request);
        if (!$data) {
            $this->error = $followModel->getError();
            return [];
        }
        if (isset($data['list']) && !$data['list']) {
            $this->error = '暂无数据';
        }
        $return['data'] = $data['list'] ?? [];
        return $return;
	}


    /**
     * 客户解绑
     * @param array $request
     * @return bool
     * @author Mr.Li
     * @create 2021-08-20 10:06
     */
    public function unbindCustomer(array $request): bool
    {
        try {
            $minId      = isset($request['min_id']) && intval($request['min_id']) ? intval($request['min_id']) : 0;
            if (!$minId) {
                $this->error = '参数错误';
                return false;
            }
            $field = ['customerId','id'];
            $info  = $this->where('id', '=', $minId)->field($field)->find();
            if (!$info) {
                $this->error = '用户信息不存在';
                return false;
            }
            if(!$info['customerId']){
                $this->error = '用户未绑定客户，无需解绑';
                return false;
            }

            $data = [
                'customerId'  => 0,
                'update_time' => date('Y-m-d H:i:s')
            ];
            $bool = $this->where('id', '=', $minId)->update($data);
            if ($bool) {
                /*删除小程序缓存*/
                $fansInfo = Cache::has('MiniProgram-'.$request['min_id']);
                if( !empty($fansInfo) ){
                    Cache::delete('MiniProgram-'.$request['min_id']);
                }

                // 操作记录
                $customerName = Db::name('crm_customer')->where('customer_id', $info['customerId'])->value('name');
                $logContentStr = "将 '绑定客户 '".$customerName.'解绑';
                $logCode       = json_encode($data, JSON_UNESCAPED_UNICODE);
                $this->addActionRecord($request['user_id'], 'admin_min_program_fans_unbind', $minId, $logContentStr, 'admin', 'min_user', $logCode);
                $this->error = '解绑成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '解绑失败';
        return false;
    }


}
